import { createStore } from "vuex";
import { saveLocal, getLocal } from "../utils/storage";
import {addRoutes} from "../router"
export default createStore({
  state: {
    tenantId: "",
    token: "",
    isAdmin: false,
    userId: "",
    refreshToken: "",
    userInfo: {},
    menus: [], // 需要渲染的菜单数据
    routes:[],
    authorityList: [],
    tentTitle: "",
    loginStatus: false, // 登录状态
    breadName: "", // 面包屑名称
    // fold:true,
  },
  getters: {
    tenantId: (state) => state.tenantId ?? getLocal("tenantId"),
    token: (state) => state.token ?? getLocal("token"),
    isAdmin: (state) => state.isAdmin ?? getLocal("isAdmin"),
    userId: (state) => state.userId ?? getLocal("userId"),
    refreshToken: (state) => state.refreshToken ?? getLocal("refreshToken"),
    userInfo: (state) => state.userInfo ?? getLocal("userInfo"),
    getMenus: (state) => state.menus ?? getLocal("menus"),
    getRoutes: (state) => state.routes ?? getLocal("routes"),
    loginStatus: (state) => state.loginStatus,
  },
  mutations: {
    // setFold(state, val: boolean) {
    //   state.fold = val;
    // },
    setBreadName(state, val: string) {
      state.breadName = val;
    },
    setTenantId(state, val: string) {
      state.tenantId = val;
      saveLocal("tenantId", val);
    },
    setToken(state, val: string) {
      state.token = val;
      saveLocal("token", val);
    },
    setRoutes(state, payload) {
      state.routes = payload;
    },
    setLoginStatus(state, val: boolean) {
      state.loginStatus = val;
    },
    setAuthorityList(state, payload) {
      state.authorityList = payload;
    },
    setIsAdmin(state, val: boolean) {
      state.isAdmin = val;
      saveLocal("isAdmin", val);
    },
    setUserId(state, val: string) {
      state.userId = val;
      saveLocal("userId", val);
    },
    setRefreshToken(state, val: string) {
      state.refreshToken = val;
      saveLocal("refreshToken", val);
    },
    setUserInfo(state, val: any) {
      state.userInfo = val;
      saveLocal("userInfo", val);
    },
    setMenus(state, val) {
      state.menus = val;
      saveLocal("menus", val);
    },
    setTentName(state, val) {
      state.tentTitle = val;
      saveLocal("tentName", val);
    },
  },
  actions: {
    login({ commit }, data) {
    },
    // 免登录
    noLogin({commit,getters,dispatch},token:string){
      if(!getters.token){
        commit("setToken", token);
        commit("setLoginStatus", true);
      }
    },
    resetToken() {},
    logout({ commit }) {
      commit("setToken", "");
      commit("setUserInfo", {});
      commit("setMenus", []);
      commit("setLoginStatus", false);
      commit("setIsAdmin", false);
      // clearLocal();
    },
    // 动态路由
    refreshRouter({getters,commit}){
      const routes = getters.routes;
      if(!Array.isArray(routes) || routes.length === 0){return ;}
      addRoutes(routes)
    }
  },
  modules: {},
});
